import React, { useCallback, useEffect, useState } from 'react';
import { Button, Tooltip, message, Modal, Form, Input } from 'antd';
import {
  CopyOutlined,
  LikeOutlined,
  DislikeOutlined,
  DeleteOutlined,
  SyncOutlined,
} from '@ant-design/icons';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import styles from '../styles/CustomControl.module.css';

import chatService from '@/api/services/chatService';

import { useContextSelector } from 'use-context-selector';
import { ChatContext } from '../context';
import useWindowWidth from '@/hooks/event/use-window-width';

import { removeRefTags } from '@/utils/regexRules';

import '../styles/reference.css'
import { removeThinkTags } from '@/utils/common';

interface CustomControlProps {
  isRobot: boolean;
  data: string;
  chatId?: string;
  dataId?: string;
  defaultLike?: boolean;
  defaultDislike?: boolean;
  onDelete?: () => void;
  onRefresh?: () => void;
}

const CustomControl: React.FC<CustomControlProps> = ({
  isRobot,
  data,
  chatId,
  dataId,
  defaultLike,
  defaultDislike,
  onDelete,
  onRefresh,
}) => {
  const [messageApi, contextHolder] = message.useMessage();
  const [form] = Form.useForm();
  const [isModalVisible, setIsModalVisible] = useState(false);

  const { shareId, appId, outLinkUid } = useContextSelector(ChatContext, (s) => s);
  const { isPc } = useWindowWidth();


  useEffect(() => {
    // console.log(isRobot, data, chatId, dataId, defaultLike, defaultDislike);
    setLiked(defaultLike || false);
    setUnLiked(defaultDislike || false);
  }, [dataId]);

  const handleCopy = useCallback(() => {
    messageApi.success('复制成功');
  }, [messageApi]);

  const handleDelete = useCallback(() => {
    if (onDelete) {
      onDelete();
    }
  }, [onDelete]);

  const handleRefresh = useCallback(() => {
    setLiked(false)
    setUnLiked(false)
    if (onRefresh) {
      onRefresh();
    }
  }, [onRefresh]);

  const [liked, setLiked] = useState(false);
  const [unLiked, setUnLiked] = useState(false);

  const handleLikeClick = () => {
    console.log(data);
    console.log(chatId);
    chatId && chatService.updateUserFeedback({
      appId: appId,
      chatId: chatId,
      dataId: dataId,
      chatItemId: dataId ?? "",
      shareId: shareId,
      outLinkUid: shareId ? outLinkUid : "",
      ...(!liked ? { userGoodFeedback: 'yes' } : {}),
    });
    setLiked(!liked);
    if (unLiked) {
      setUnLiked(false);
    }
  };

  /* const handleDislikeClick = () => {
    setIsModalVisible(true);
    !unLiked && setIsModalVisible(true);
    unLiked && handleModalOk();
    form.resetFields();
  }; */
  const handleDislikeClick = () => {
    if (!unLiked) {
      setIsModalVisible(true);
      form.resetFields();
    } else {
      // setUnLiked(false);
      handleModalOk();
    }
  };

  const [selectedOptions, setSelectedOptions] = useState<string[]>([]);

  const handleOptionClick = (option: string) => {
    const currentOptions = form.getFieldValue('feedbackOptions') || [];
    const newOptions = currentOptions.includes(option)
      ? currentOptions.filter((item: string) => item !== option)
      : [...currentOptions, option];
    form.setFieldsValue({ feedbackOptions: newOptions });

    setSelectedOptions(newOptions);
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      // 新增：将 feedbackOptions 和 feedbackMessage 拼接
      const feedbackOptions = values.feedbackOptions || [];
      const feedbackMessage = values.feedbackMessage || '';
      const allFeedback = [...feedbackOptions, feedbackMessage].filter(Boolean).join('|');
      chatId &&
        chatService.updateUserFeedback({
          appId: appId,
          chatId: chatId,
          dataId: dataId,
          chatItemId: dataId ?? "",
          shareId: shareId,
          outLinkUid: shareId ? outLinkUid : "",
          ...(!unLiked ? { userBadFeedback: allFeedback ? allFeedback : '用户没有填写具体反馈内容' } : {}),
        });
      setUnLiked(!unLiked);
      !unLiked && messageApi.success('反馈提交成功');
      form.resetFields();
      setSelectedOptions([]);
      setIsModalVisible(false);
    } catch (error) {
      !unLiked && messageApi.error('反馈提交失败');
    }
  };

  const handleModalCancel = () => {
    setIsModalVisible(false);
  };

  useEffect(() => {
    setLiked(defaultLike === true);
  }, [defaultLike])

  useEffect(() => {
    setUnLiked(defaultDislike === true);
  }, [defaultDislike])

  return (
    <>

      <Modal
        className={`${!isPc && 'feedback-modal'}`}
        title={<div style={{ padding: 0, margin: 0 }}>不满意反馈</div>}
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={handleModalCancel}

        footer={[
          /*   <Button key="back" onClick={handleModalCancel}>
              取消
            </Button>, */
          <div
            key="submit-button"
            style={{
              width: '100%',
              display: 'flex',
              justifyContent: 'center',
            }}
          >
            <Button
              type="primary"
              onClick={handleModalOk}
              style={{
                width: '100%',
                maxWidth: '300px', // 可根据需要调整最大宽度
                padding: '12px 0', // 增加垂直内边距，使按钮高度适中
              }}
            >
              提交反馈
            </Button>
          </div>,
        ]}


        style={
          !isPc
            ? {
              top: 'unset',
              bottom: 0,
              margin: 0,
              position: 'fixed',
              width: '100%',
              maxWidth: '100%',
              paddingBottom: 0,
              maxHeight: '48vh',
              left: 0,
            }
            : {}
        }


      >
        <Form form={form} layout="vertical" name="form_in_modal">
          <Form.Item name="feedbackOptions">
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
              {['没有回答我的问题', '答案太长不想看', '试过了没有用', '看不懂'].map((option) => (
                <Button
                  key={option}
                  type={selectedOptions.includes(option) ? 'primary' : 'default'}
                  onClick={() => handleOptionClick(option)}
                  style={{ borderRadius: '16px' }}
                >
                  {option}
                </Button>
              ))}
            </div>
          </Form.Item>
          <Form.Item
            name="feedbackMessage"
            rules={[
              {
                required: false,
              },
            ]}
          >
            <Input.TextArea rows={4} style={{ resize: 'none' }}
              placeholder="您可以在此输入详细的反馈（可选）"
            />
          </Form.Item>
        </Form>
      </Modal>

      <div className='flex gap-1 custom-control'>
        {contextHolder}
        <Tooltip title="复制">
          <CopyToClipboard text={removeThinkTags(removeRefTags(data))?.trim()} onCopy={handleCopy}>
            <Button
              icon={<CopyOutlined />}
              style={{ border: 'none', background: 'none' }}
              size="small"
            />
          </CopyToClipboard>
        </Tooltip>
        {isRobot ? (
          <>
            {chatId ? (
              <Tooltip title="点赞">
                <Button
                  icon={<LikeOutlined />}
                  style={{
                    border: 'none',
                    color: liked ? '#12B76A' : '#000',
                    background: 'none',
                    display: unLiked ? 'none' : 'inline-block',
                  }}
                  size="small"
                  onClick={handleLikeClick}
                />
              </Tooltip>
            ) : (
              liked &&<Button
                icon={<LikeOutlined />}
                disabled={true}
                style={{
                  border: 'none',
                  color: liked ? '#12B76A' : '#000',
                  background: 'none',
                  display: unLiked ? 'none' : 'inline-block',
                }}
                size="small"
              />
            )}

            {chatId ? (
              <Tooltip title="反馈">
                <Button
                  icon={<DislikeOutlined />}
                  style={{
                    border: 'none',
                    color: unLiked ? 'red' : '#000',
                    background: 'none',
                    display: liked ? 'none' : 'inline-block',
                  }}
                  size="small"
                  onClick={handleDislikeClick}
                />
              </Tooltip>
            ) : (
              unLiked && <Button
                icon={<DislikeOutlined />}
                disabled={true}
                style={{
                  border: 'none',
                  color: unLiked ? 'red' : '#000',
                  background: 'none',
                  display: liked ? 'none' : 'inline-block',
                }}
                size="small"
              />
            )}
            {onRefresh && (
              <Tooltip title="重新生成">
                <Button
                  icon={<SyncOutlined />}
                  onClick={handleRefresh}
                  style={{ border: 'none', background: 'none' }}
                  size="small"
                />
              </Tooltip>
            )}
          </>
        ) : (
          <>
            {onRefresh && (
              <Tooltip title="重新生成">
                <Button
                  icon={<SyncOutlined />}
                  onClick={handleRefresh}
                  style={{ border: 'none', background: 'none' }}
                  size="small"
                />
              </Tooltip>
            )}
            {/* <div className={styles['divider']}></div> */}
            {onDelete && (
              <Tooltip title="删除">
                <Button
                  icon={<DeleteOutlined />}
                  onClick={handleDelete}
                  style={{ border: 'none', background: 'none' }}
                  size="small"
                />
              </Tooltip>
            )}
          </>
        )}
      </div>
    </>
  );
};

export default CustomControl;
